<template>
    <view style="height: 100%">
        <view v-if="address == ''" class="toAddress" @tap="toAddress">
            <text>添加地址</text>
        </view>
        <view class="header" v-else>
            <view class="distribution">配送信息</view>
            <view class="address" @tap="toAddress">
                <view class="user">
                    <text class="name">{{ address.username }}</text>
                    <text class="tel">{{ address.mobile }}</text>
                </view>
                <view class="ress">{{ address.address }}</view>
            </view>
            <view class="xian xian2"></view>
        </view>
        <view class="box">
            <text class="title">订单清单</text>
            <view class="list">
                <block v-for="(item, index) in allGoods" :key="index">
                    <view class="item">
                        <text class="left">{{ item.name }}(x{{ item.buycount }})</text>
                        <text class="right">¥{{ item.pay }}</text>
                    </view>
                </block>
                <view class="fot">
                    <text class="left">实际支付</text>
                    <text class="right">¥{{ sumPrice }}</text>
                </view>
            </view>
        </view>
        <view class="footer">
            <view class="left">
                <text class="p">总价:</text>
                <text class="span">¥{{ sumPrice }}</text>
            </view>
            <view class="right">
                <button @tap="settlement">支付</button>
            </view>
        </view>
    </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
var util = require('../../utils/util.js');
export default {
    data() {
        return {
            userInfo: {},
            allGoods: {},
            sumPrice: 0,
            address: {
                username: '',
                mobile: '',
                address: ''
            }
        };
    },
    onLoad: function () {
        var that = this;
        let userInfo = uni.getStorageSync('user');
        that.setData({
            userInfo: userInfo
        });
    },
    onShow: function () {
        var allGoods = uni.getStorageSync('shoppingcar');
        var sumPrice = 0;
        for (var i = 0; i < allGoods.length; i++) {
            var price = allGoods[i].price;
            var count = allGoods[i].buycount;
            price = util.accMul(price, count);
            if (allGoods[i].discount && allGoods[i].discount > 0) {
                var discount = allGoods[i].discount;
                price = util.accMul(price, discount);
            }
            allGoods[i].pay = price;
            sumPrice = util.accAdd(sumPrice, price);
        }
        this.setData({
            allGoods: allGoods,
            sumPrice: sumPrice
        });
        this.getDefaultAddress();
    },
    methods: {
        toAddress: function () {
            uni.navigateTo({
                url: '/pages/address/index'
            });
        },

        getDefaultAddress: function () {
            //获取地址
            var that = this;
            var data = {
                userId: this.userInfo.userId
            };
            http.httpGet(config.clubApi.getAddressList, data, function (res) {
                if (res.code == '200') {
                    var allAddress = res.data;
                    var address = '';
                    for (var i = 0; i < allAddress.length; i++) {
                        if (allAddress[i].isfirst == 1) {
                            address = allAddress[i];
                            break;
                        }
                    }
                    if (address == '' && allAddress.length > 0) {
                        address = allAddress[0];
                    }
                    that.setData({
                        address: address
                    });
                }
            });
        },

        createOrder: function (buyGoods, callback) {
            http.httpPut(config.clubApi.createOrder, buyGoods, function (res) {
                if (res.code == '200') {
                    //订单创建成功
                    if (typeof callback == 'function') {
                        callback(res);
                    }
                } else {
                    //订单创建失败
                    if (typeof callback == 'function') {
                        callback('');
                    }
                }
            });
        },

        settlement: function () {
            var that = this;
            //检查地址是否为空
            if (this.address == '') {
                uni.showModal({
                    title: '提示',
                    content: '请您先添加邮寄地址！',
                    success: function (res) {
                        if (res.confirm) {
                            that.toAddress();
                        }
                        return;
                    }
                });
            }
            //继续生成订单
            var addressid = this.address.id;
            var allGoods = this.allGoods;
            var userId = this.userInfo.userId;
            var buyGoods = [];
            allGoods.forEach(function (goods) {
                var amount = util.accMul(goods.price, goods.buycount);
                var data = {
                    appId: config.APPID,
                    shopId: goods.shopId,
                    productId: goods.id,
                    amount: amount,
                    discount: goods.discount,
                    payAmount: goods.pay,
                    num: goods.buycount,
                    addressId: addressid,
                    createBy: userId
                };
                buyGoods.push(data);
            });
            this.createOrder(buyGoods, function (res) {
                if (res.code == '200') {
                    try {
                        let params = res.data;
                        WeixinJSBridge.invoke('getBrandWCPayRequest', params, function (res) {
                            if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'none',
                                    duration: 3000
                                });
                            } else {
                                uni.showToast({
                                    title: '支付失败',
                                    icon: 'none',
                                    duration: 3000
                                });
                            }
                            uni.setStorageSync('shoppingcar', []);
                            uni.navigateBack();
                        });
                    } catch (f) {
                        console.log('CatchClause', f);
                        console.log('CatchClause', f);
                        if (res.msg) {
                            uni.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                        uni.setStorageSync('shoppingcar', []);
                        uni.navigateBack({
                            delta: 2
                        });
                    }                    
                    uni.setStorageSync('shoppingcar', []);
                    uni.navigateBack({
                        delta: 3
                    });
                }
            });
        }
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
